<template>
  <div>
    <!-- 头部面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主题卡片区 -->
    <el-card>
      <!-- alert提示区 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条显示区 -->
      <el-steps :space="300" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          :stretch="true"
          v-model="activeIndex"
          :before-leave="changeTabs"
          @tab-click="tabsChange"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyInfo" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="val" v-for="(val,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyInfo" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
              :on-success="uploadsuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor></quill-editor>
            <el-button type="primary" @click="addgoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览对话框 -->
      <el-dialog title="图片预览" :visible.sync="previewdialogVisible" width="50%">
        <img :src="uploadPath" class="previewImg" />
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
// 配置lodash
import _ from 'lodash'

export default {
  data() {
    return {
      tabPosition: [],
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      cateList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      manyInfo: [],
      onlyInfo: [],
      uploadURL: 'http://www.klxin.cn:8888/api/private/v1/upload',
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewdialogVisible: false,
      uploadPath: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 商品分类列表 商品分类是级联选择框，需要获取所有层级的分类
    async getCateList() {
      const res = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      // console.log(res)
      this.cateList = res.data
    },
    // 级联选择框发生变化的时候触发
    handleChange() {
      // console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        return (this.addForm.goods_cat = [])
      }
    },
    // 当tabs切换的时候触发,返回从哪个到哪个，如果返回false阻止切换
    changeTabs(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 当tabs发生切换时触发，发送请求，获取参数和属性数据
    async tabsChange() {
      if (this.activeIndex === '1') {
        const res = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数数据失败')
        }

        res.data.forEach(val => {
          return (val.attr_vals =
            val.attr_vals.trim().length === 0 ? [] : val.attr_vals.split(' '))
        })
        this.manyInfo = res.data
      } else if (this.activeIndex === '2') {
        const res = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数数据失败')
        }
        this.onlyInfo = res.data
      }
    },
    // 图片预览 点击图片名称预览图片
    handlePreview(file) {
      // console.log(file)
      this.uploadPath = file.response.data.url
      this.previewdialogVisible = true
    },
    // 移除图片
    handleRemove(file) {
      // console.log(file)
      const romveImg = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => {
        return item.pic === romveImg
      })
      // console.log(index)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },
    // 当图片上传成功的时候触发 保存图片的临时路径到addForm.pics数组中
    uploadsuccess(response) {
      // console.log(response)
      const picPath = response.data.tmp_path
      this.addForm.pics.push({ pic: picPath })
      // console.log(this.addForm.pics)
    },
    // 确定添加商品
    addgoods() {
      // 验证表单
      this.$refs.addFormRef.validate(async val => {
        if (!val) {
          return this.$message.error('请填写必要的表单项!')
        }
        // 验证成功  将goods_cat转换为以为','分割的 因为定义是数组，所以需要深拷贝再操作
        const addform = _.cloneDeep(this.addForm)
        addform.goods_cat = addform.goods_cat.join(',')
        // console.log(addform.goods_cat) // 转为 351,356,365 以，号分割的字符串
        // 获取addForm.attrs（数组），包含 动态参数 和 静态属性
        this.manyInfo.forEach(item => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(obj)
        })
        this.onlyInfo.forEach(item => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(obj)
        })
        // console.log(this.addForm.attrs)
        // 给深拷贝的addform定义attrs属性，并赋值
        addform.attrs = this.addForm.attrs
        // console.log(addform)
        // 发送请求，添加商品
        const res = await this.$http.post('goods', addform)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('商品添加失败')
        }
        this.$message.success('商品添加成功')
        // 跳转到商品列表页
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 直接当做普通属性调用不加括号
    // 任何data中数据变化立即重新计算
    // 计算属性会缓存
    // 获取三级分类的id
    cateID() {
      if (this.addForm.goods_cat.length !== 3) {
        return null
      } else {
        return this.addForm.goods_cat[2]
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-alert__title {
  font-size: 20px;
}
.el-checkbox {
  margin: 0 0 10px 10px;
}
.previewImg {
  width: 100%;
}
.el-button {
  margin-top: 15px;
}
</style>
